<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="卡片编号">
          <el-input
            v-model="queryParams.keywords"
            placeholder="卡片编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button type="success" @click="exportVipCards()"><i class="el-icon-upload2"></i> 导出 VIP 卡片</el-button>
        <el-button type="success" @click="exportVipSample()"><i class="el-icon-upload2"></i> 导出 VIP 样本</el-button>
        <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i class="el-icon-delete"></i> 删除</el-button>
      </template>
      <p>注意：卡片编号为 <el-tag type="info" size="medium">灰色</el-tag> 表示不可用，
        点击 <span style="font-style: italic; font-weight: 600;;">导出 VIP 卡片</span> 之后，卡片变为可用状态，用户才可以绑定。</p>
      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="卡片编号" prop="number">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.available" size="medium">{{ scope.row.number }}</el-tag>
            <el-tag v-else type="info" size="medium">{{ scope.row.number }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="卡片密码" prop="pwd"/>
        <el-table-column label="包含样本数" prop="num"/>
        <el-table-column label="卡片状态" prop="vipCardStatus"/>
        <el-table-column label="备注" prop="desc"/>
        <el-table-column label="创建时间" prop="createTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="280" width="520">
          <template #default="scope">
            <el-button type="warning" size="small" link @click="openDescDialog(scope.row.id)"><i class="el-icon-edit"></i> 编辑备注</el-button>
            <el-button type="warning" size="small" link @click="openSampleDialog(scope.row.id)"><i class="el-icon-view"></i> 查看样本</el-button>
            <el-button type="primary" size="small" link :disabled="!(scope.row.expressId != null && scope.row.expressSfNo == null)" @click="openExpressDetailDialog(scope.row)"><i class="el-icon-headset"></i> 呼叫快递</el-button>
            <el-button type="primary" size="small" link :disabled="scope.row.expressSfNo == null" @click="openExpressDialog(scope.row)"><i class="el-icon-monitor"></i> 物流信息</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="500px"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
        <!-- <el-form-item label="卡片编号" prop="number">
          <el-input v-model="formData.number" placeholder="请输入卡片编号" />
        </el-form-item> -->
        <!-- <el-form-item label="设置卡片密码" prop="pwd">
          <el-input v-model="formData.pwd" placeholder="请输入卡片密码" />
        </el-form-item> -->
        <el-form-item label="VIP 卡片数" prop="cardNum">
          <el-input-number v-model="formData.cardNum" controls-position="right" :min="1" :max="99" size="medium"></el-input-number>
        </el-form-item>
        <el-form-item label="每个卡片包含样本数" prop="num">
          <el-input-number v-model="formData.num" controls-position="right" :min="1" :max="99" size="medium"></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="desc">
          <el-input type="textarea" :rows="6" placeholder="请输入备注" v-model="formData.desc"></el-input>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="editCardDescDiaglog" title="编辑备注" width="500px" :before-close="closeEditDescDialog">
      <el-form ref="userFormRef1" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="备注" prop="desc">
          <el-input type="textarea" :rows="6" placeholder="请输入备注" v-model="formData.desc"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addDesc">确 定</el-button>
          <el-button @click="closeEditDescDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="sampleListDialog.visible" :title="sampleListDialog.title" width="1000px" :before-close="closeSampleListDialog" :close-on-click-modal="false">
      <el-table v-loading="loading" :data="sampleList" highlight-current-row border :cell-style="cellStyle" @cell-click="openDetail">
        <el-table-column label="序号" width="55" prop="dataIndex" />
        <el-table-column label="样本编号" prop="number" width="170"/>
        <el-table-column label="用户" prop="userName" />
        <el-table-column label="手机号" prop="phone" />
        <el-table-column label="样本状态" prop="statusText" />
        <el-table-column label="更新时间" prop="updateTimeText" width="170"/>
        <el-table-column fixed="right" label="操作" min-width="120" width="120">
          <template #default="scope">
            <el-button type="danger" size="small" link @click="deleteSample(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>

    <el-dialog :visible.sync="detailDialog.visible" :title="detailDialog.title" width="500px"
      :before-close="closeDetailDialog">
      <div>
        <p><span>样本编号：</span><span>{{ checkedSample.number }}</span></p>
        <p style="margin-top: 8px;"><span>样本状态：</span><span>{{ checkedSample.statusText }}</span></p>
        <p style="margin-top: 8px;"><span>更新时间：</span><span>{{ checkedSample.updateTimeText }}</span></p>
        <p style="margin-top: 8px;"><span>创建时间：</span><span>{{ checkedSample.createTimeText }}</span></p>
        <img :src="sampleImgUrl" style="margin-top: 10px; width: 320px;" />
      </div>
    </el-dialog>

    <el-dialog :visible.sync="expressDialog.visible" :title="expressDialog.title"  width="800px" :close-on-click-modal="false" :before-close="closeExpressDialog">
      <el-table v-loading="loading" :data="expressRouterList" highlight-current-row border>
        <el-table-column label="地址" prop="acceptAddress"/>
        <el-table-column label="时间" prop="acceptTime"/>
        <el-table-column label="备注" prop="remark"/>
      </el-table>
    </el-dialog>

    <el-dialog :visible.sync="expressDetailDialog.visible" :title="expressDetailDialog.title"  width="800px" :close-on-click-modal="false" :before-close="closeExpressDetailDialog">
      <p style="margin-bottom: 10px;">快递备注：<span style="color: red;">vip卡号：{{ checkedCard.number }}</span></p>
      <el-descriptions border :column="2">
        <el-descriptions-item label="发件人姓名" label-class-name="descLabelClass" content-class-name="descLabelClass">
          <el-input v-if="updateExpressInfoFlag" v-model="expressInfo.name"/>
          <template v-if="!updateExpressInfoFlag">{{ expressInfo.name }}</template>
        </el-descriptions-item>
        <el-descriptions-item label="发件人手机号" label-class-name="descLabelClass" content-class-name="descLabelClass">
          <el-input v-if="updateExpressInfoFlag" v-model="expressInfo.phone"/>
          <template v-if="!updateExpressInfoFlag">{{ expressInfo.phone }}</template>
        </el-descriptions-item>
        <el-descriptions-item label="发件人地址" label-class-name="descLabelClass" content-class-name="descLabelClass">
          <el-input v-if="updateExpressInfoFlag" v-model="expressInfo.addr"/>
          <template v-if="!updateExpressInfoFlag">{{ expressInfo.addr }}</template>
        </el-descriptions-item>
        
      </el-descriptions>
      <el-descriptions border :column="2">
        <el-descriptions-item label="收件人姓名" label-class-name="descLabelClass" content-class-name="descLabelClass">
          <el-input v-if="updateExpressInfoFlag" v-model="expressInfo.receiveName"/>
          <template v-if="!updateExpressInfoFlag">{{ expressInfo.receiveName }}</template>
        </el-descriptions-item>
        <el-descriptions-item label="收件人手机号" label-class-name="descLabelClass" content-class-name="descLabelClass">
          <el-input v-if="updateExpressInfoFlag" v-model="expressInfo.receivePhone"/>
          <template v-if="!updateExpressInfoFlag">{{ expressInfo.receivePhone }}</template>
        </el-descriptions-item>
        <el-descriptions-item label="收件人地址" label-class-name="descLabelClass" content-class-name="descLabelClass">
          <el-input v-if="updateExpressInfoFlag" v-model="expressInfo.receiveAddr"/>
          <template v-if="!updateExpressInfoFlag">{{ expressInfo.receiveAddr }}</template>
        </el-descriptions-item>
      </el-descriptions>
      <el-button type="primary" @click="placeOrder()" style="margin-top: 10px; margin-left: 10px; float: right;">呼叫快递</el-button>
      <el-button type="warning" v-if="!updateExpressInfoFlag" @click="updateExpressInfoFlag = true" style="margin-top: 10px; float: right;">更新信息</el-button>
    </el-dialog>

  </div>
</template>

<script>
import expressApi from '@/api/aliyun/detection/express'
import sampleApi from '@/api/aliyun/detection/sample'
import vipCardApi from '@/api/aliyun/detection/vipCard'
import { formatDate } from '@/utils/formatTime'
export default {
	name: 'userIndex',
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {},

      statusMap: {
        CREATE: '已创建',
        TO_BE_SENT_OUT: '待寄出',
        SENT_OUT: '已寄出',
        SAMPLE_RECEIVE: '样本已收到',
        REPORT_SEQ_END: '实验室测序完成',
        DATA_ANALYSIS: '数据分析中',
        REPORT_AUDIT: '样本审核中',
        COMPLETED: '完成',
      },

      vipCardStatusMap: {
        NON_BIND: '未绑定',
        BIND: '已绑定'
      },

      sampleList: [],
      sampleListDialog: {},
      detailDialog: {},
      checkedSample: {},
      sampleImgUrl: '',

      expressRouterList: [],
      expressDialog: {},
      expressDetailDialog: {},
      expressInfo: {},
      updateExpressInfoFlag: false,
      checkedCard: {},

      editCardDescDiaglog: false,
		};
	},
  methods: {
    addDesc () {
      vipCardApi.updateDesc(this.formData).then(res => {
        this.$message({ message: '备注修改成功！', type: 'success' });
        this.closeEditDescDialog()
        this.handleQuery()
      })
    },
    closeEditDescDialog () {
      this.editCardDescDiaglog = false;
    },
    openDescDialog (id) {
      this.editCardDescDiaglog = true;
      vipCardApi.get(id).then((res) => {
        let data = res.data;
        this.formData = data;
      });
    },
    exportVipCards () {
      this.$confirm('vip 卡片导出之后，用户可以绑定，且卡片将不能再次导出, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vipCardApi.exportUpdateCards().then(res => {
          let blob = new Blob([res],{type: 'application/vnd.ms-excel'});
          const blobURL = window.URL.createObjectURL(blob)
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', 'VIP 卡片信息.xlsx')
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
        })
      }).catch(() => {});
    },
    exportVipSample () {
      vipCardApi.exportVipSample().then(res => {
        let blob = new Blob([res],{type: 'application/vnd.ms-excel'});
        const blobURL = window.URL.createObjectURL(blob)
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', 'VIP 样本信息.xlsx')
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
      })
    },
    placeOrder () {
      if (this.updateExpressInfoFlag) {
        expressApi.updateBasic(this.expressInfo).then(res => {
          expressApi.placeOrder(this.expressInfo.id).then(res => {
            this.$message({ message: '已成功下单！', type: 'success' });
            this.closeExpressDetailDialog();
            this.handleQuery();
          })
        })
      } else {
        expressApi.placeOrder(this.expressInfo.id).then(res => {
          this.$message({ message: '已成功下单！', type: 'success' });
          this.closeExpressDetailDialog();
          this.handleQuery();
        })
      }
    },
    closeExpressDetailDialog () {
      this.$set(this.expressDetailDialog, 'visible', false);
    },
    openExpressDetailDialog (row) {
      this.checkedCard = row;
      this.updateExpressInfoFlag = false;
      this.$set(this.expressDetailDialog, 'visible', true);
      this.$set(this.expressDetailDialog, 'title', '快递信息');
      expressApi.get(row.expressId).then(res => {
        this.expressInfo = res.data;
      })
    },
    closeExpressDialog () {
      this.$set(this.expressDialog, 'visible', false);
    },
    openExpressDialog (row) {
      this.$set(this.expressDialog, 'visible', true);
      this.$set(this.expressDialog, 'title', '快递信息');
      this.loading = true;
      expressApi.routers(row.expressId).then(res => {
        this.expressRouterList = res.data.routeDtos;
        this.loading = false;
      })
    },
    deleteSample (id) {
      sampleApi.delete(id).then((res) => {
        this.$message({ message: '样本删除成功！', type: 'success' });
        vipCardApi.sampleList(id).then(res => {
          let data = res.data;
          let index = 1;
          data.forEach(v => {
            v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
            v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
            v.statusText = this.statusMap[v.status];
            v.dataIndex = index++;
          })
          this.sampleList = data;
        })
      });
    },
    closeSampleListDialog () {
      this.$set(this.sampleListDialog, 'visible', false);
    },
    openSampleDialog (id) {
      this.$set(this.sampleListDialog, 'visible', true);
      this.$set(this.sampleListDialog, 'title', '样本列表');
      vipCardApi.sampleList(id).then(res => {
        let data = res.data;
        let index = 1;
        data.forEach(v => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.statusText = this.statusMap[v.status];
          v.dataIndex = index++;
        })
        this.sampleList = data;
      })
    },
    openDetail(row, column) {
      if (column.property == "number") {
        this.$set(this.detailDialog, 'visible', true);
        this.$set(this.detailDialog, 'title', '样本详情');
        this.checkedSample = row;
        this.sampleImgUrl = 'https://w66h994817.zicp.fun/platform/aliyun-api/sample/gene-barcode/' + row.number
      }
    },
    closeDetailDialog () {
      this.$set(this.detailDialog, 'visible', false);
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      vipCardApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.vipCardStatus = this.vipCardStatusMap[v.status];
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        vipCardApi.update(this.formData).then((res) => {
          this.$message({message: 'vip 卡片更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        vipCardApi.addBatch(this.formData).then((res) => {
          this.$message({message: 'vip 卡片批量添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑vip卡片');
        vipCardApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;

        });
      } else {
        this.$set(this.dialog, 'title', '新增vip卡片');
        that.formData = {
          num: 1,
          cardNum: 1
        };
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          vipCardApi.delete(id).then((res) => {
            this.$message({message: 'vip卡片删除成功！', type: 'success'});
            this.handleQuery();
          });
        }).catch(() => {
        });
      } else {
        this.$message.error('暂不支持批量删除vip卡片！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property == "number") {
        return {
          "cursor": "pointer"
        }
      }
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
/deep/.descLabelClass {
  width: 120px;
}
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>